package com.atguigu.threadtest;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ClassName: DemoteLock
 * Package: com.atguigu
 * Description:
 *
 * @author: fu-wang
 * @create: 2024/10/28 20:28
 * version: 1.0
 */
public class DemoteLock {//锁降级就是为了提高效率，在释放写锁的时候获取到读锁，因为读读可并发，注意点：释放前一定要获取到读锁
    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void Demote(){
        System.out.println("加入写锁...");
        readWriteLock.writeLock().lock();

        System.out.println("加入读锁...");
        readWriteLock.readLock().lock();

        System.out.println("释放写锁");
        readWriteLock.writeLock().unlock();

        System.out.println("释放读锁");
        readWriteLock.readLock().unlock();
    }
}
class DemoteLockTest{
    public static void main(String[] args) {
        DemoteLock demoteLock = new DemoteLock();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                demoteLock.Demote();
            }

        },"thread Demote").start();
    }
}
